package com.example.chinamobileai.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chinamobileai.config.MyChatMemory;
import com.example.chinamobileai.domain.ChatHistory;
import com.example.chinamobileai.mapper.ChatHistoryMapper;
import com.example.chinamobileai.mapper.ConversationMapper;
import com.example.chinamobileai.service.IChatHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ChatHistoryImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory> implements IChatHistoryService {

    /**
     * 保存会话历史
     * @param type 类型
     * @param chatId 会话ID
     */
    @Override
    public void saveChatHistory(String type,String chatId) {
        // 判断当前会话历史是否已经保存
        Long count = lambdaQuery()
                .eq(ChatHistory::getConversationId, chatId)
                .eq(ChatHistory::getType, type)
                .count();
        // 如果已经保存，则返回
        if (count > 0) {
            return;
        }
        // 保存会话历史
        save(ChatHistory.builder()
                .conversationId(chatId)
                .type(type)
                .title("会话"+chatId)
                .createTime(LocalDateTime.now())
                .userId(null)
                .build());

    }
    /**
     * 获取会话历史conversationId
     * @param type 类型
     * @param userId 用户ID
     * @return 会话历史
     */
    @Override
    public List<String> getChatIds(String type, Long userId) {

        return lambdaQuery()
                .eq(ChatHistory::getType, type)
                .eq(userId != null,ChatHistory::getUserId, userId)
                .orderByAsc(ChatHistory::getCreateTime)
                .list()
                .stream()
                .map(ChatHistory::getConversationId)
                .toList();
    }
}